from django.shortcuts import render,HttpResponse
from crm import models
from StudentCRM import settings
import os
from crm.permissions import permission

# Create your views here.

@permission.check_permission
def stu_my_classes(request):
    return render(request, "student/my_classes.html")

@permission.check_permission
def studyrecords(request, enroll_obj_id):
    enroll_obj = models.Enrollment.objects.get(id=enroll_obj_id)
    return render(request, "student/studyrecords.html", {"enroll_obj": enroll_obj})

@permission.check_permission
def homework_detail(request, studyrecord_id):
    studyrecord_obj = models.StudyRecord.objects.get(id=studyrecord_id)
    if request.method == "POST":
        print(request.FILES)
        if request.is_ajax():
            print("ajx-post-file", request.FILES)
            homework_data_dir = "%s/%s/%s/%s/" % (settings.HOMEWORKS_DATA,
                                                  studyrecord_obj.student.enrolled_class_id,
                                                  studyrecord_obj.course_record_id,
                                                  studyrecord_obj.id)
            if not os.path.exists(homework_data_dir):
                os.makedirs(homework_data_dir, exist_ok=True)
            for k, file_obj in request.FILES.items():
                with open("%s/%s" % (homework_data_dir, file_obj.name), "wb") as f:
                    for chunk in file_obj.chunks():
                        f.write(chunk)
            return HttpResponse("success")
    return render(request, "student/homework_detail.html", {"studyrecord_obj": studyrecord_obj})
